<template>
  <div>
    <div id="strategy" style="padding-top:85px;">
      <div id="strategynav" style="display: flex;flex-direction: row;justify-content: space-between;height:60px;align-items: center;">
        <div style="margin-left: 20px;margin-top: 7px;display:flex;flex-direction: row;align-items: center;">
            <i class="iconfont icon-fanhui pointer" @click="back"></i>
          <div style="font-size:20px;" class="pointer">{{strategy_name}}</div>
        </div>
        <div style="margin-right:20px;display:flex;flex-direction: row;">
          <div class=" active pointer"  style="font-size:18px;margin-right:10px;">编辑策略</div>
          <div class="strategynav_right pointer" style="font-size:18px;" @click="huiceliebiao">回测详情</div>
        </div>
      </div>
      <div class="strategyedit">
        <div class id="compile-editor-div">
          <editor id="editor"  @blur.native.capture="changeData" v-model="content"  @init="editorInit" @setCompletions="setCompletions" theme="chaos" lang="java" fontSize='20px'  width="750" height="805" ></editor>
        </div>
        <div style="display:flex;width: calc(100% - 750px); flex-direction:column;">
          <div id="strategy_backtest">
            <div id="bavktestnav">
              <div style="display: flex;flex-direction: row;align-items: center;">
                <span style="margin:0px 5px 0px 20px;">时间</span>
                <el-date-picker
                  :picker-options="pickerDisabled"
                  unlink-panels
                  style="margin-right:20px"
                  v-model="time"
                  type="daterange"
                  format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
                <!-- <input id="sdate" class="text" type="date" value="2016-06-01" />
                <span>—</span>
                <input id="edate" class="text" type="date" value="2017-06-01" />-->
                <span style="margin-right:5px;">时间周期</span>
                <!-- <input class="input" style="height:40px;" />  -->
                <el-select v-model="runTimeCycle" placeholder="请选择">
                  <el-option key="1" label="1分钟" value="1"></el-option>
                  <el-option key="2" label="15分钟" value="2"></el-option>
                  <el-option key="3" label="30分钟" value="3"></el-option>
                  <el-option key="4" label="1小时" value="4"></el-option>
                  <el-option key="5" label="2小时" value="5"></el-option>
                  <el-option key="6" label="1天" value="6"></el-option>
                  <el-option key="7" label="2天" value="7"></el-option>
                  <el-option key="8" label="7天" value="8"></el-option>
                </el-select>
              </div>
              <input style="margin:0px 20px" type="button" value="运行回测" class="btn bgbtn02 pointer"  @click="yunxinghuice"/>
            </div>
          </div>
          <!--回测图-->
          <div >
            <div style="width: 100%;height:650px;" id="backtest_chart"></div>
          </div>
          <!-- <div v-else style="width: 100%;height:600px;"  >
            <div style="display:flex;justify-content:center;align-items:center;height:550px">
              <i class="iconfont icon-dengdai" ></i>
            </div>
          </div> -->
        </div>
        
      </div>
    </div>
  </div>
</template>
<style>
.el-range-separator{
  width: 10%;
}
.el-range-editor.el-input__inner {
    display: inline-flex;
    -webkit-box-align: center;
    align-items: center;
}
.el-scrollbar__view{
    margin-bottom: 21px;
}

</style>
<style scoped>
.input{
  border: none;
  border-radius: 4px;
}
.strategyedit{
  display: flex;
  flex-direction: row;
}
.strategynav_right:hover{
    color: #337ab7;
}
.active {
  color: #255da8;
  border-bottom: 4px solid #255da8;
}
.iconfont{
  font-size: 25px;
}
.ace_editor{
    font: 20px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
}
/*回测框*/
/*1.回测框导航栏*/
#bavktestnav {
  height: 60px;
  background-color: #e8ecf0;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content:space-between;
}
.btn {
  padding-bottom: 20px;
  padding: 6px 18px;
  border-radius: 4px;
  background-color: #337ab7;
  color: #fff;
  cursor: pointer;
}
.el-input__inner{
  width:400px;
}
</style>
<script>
import moment from "moment"
export default {
    name:'aceEditor',
    components: {
        editor: require('vue2-ace-editor')
    },
  data() {
    return {
      strategyId:'',
      SessionToken:'',
      content:'',
      userflag: false,
      strategy_name: "",
      time:'',
      pickerDisabled: {
        disabledDate:(time) => {
          return time.getTime() > new Date() * 1 + 600 * 1000;
        }
      },
      runTimeCycle:'',
      drawdata:'',
      drawvalue:[],
      drawdate:[],
      backtestId:'',
      runflag:'',
    }
  },
  mounted(){
    this.strategyId = localStorage.getItem('strategyId')
    this.SessionToken = localStorage.getItem('SessionToken')
    // this.backtestId = localStorage.getItem('backtestId')
    this.getStrategy()
    this.drawbacktestcharts()
    this.getStratrgyCode()
    if(this.backtestId !== null && this.backtestId !== ''){
      this.interval = setInterval(this.getOrderList,2000)
    }
  },
  methods: {
    getStrategy(){
      this.$http.post('getStrategy?sessionToken='+this.SessionToken+'&id='+this.strategyId+'').then((resp) => {
        if (resp.data.status === 200) {
          console.log(resp)
          this.strategy_name = resp.data.data.strategyname
            // this.$message.success(resp.data.message)
         } else {
          this.$message.error('获取策略详情失败！')
        }
      })
    },
    getOrderList(){
      console.log('定时器运行')
      this.$http.get('inquireIsRunOver?sessionToken='+this.SessionToken+'&recordId='+this.backtestId+'').then((resp) => {
        if (resp.data.status === 200) {
          console.log(resp)
          this.runflag = resp.data.data
          if(this.runflag === 2){
            //获取收益图表数据
            this.$http.get('getTradingAccountMsg?sessionToken='+this.SessionToken+'&recordId='+this.backtestId+'').then((resp) => {
              if (resp.data.status === 200) {
                this.drawdata=resp.data.data
                console.log(this.drawdata)
              } else {
                console.log(resp)
                this.$message.error(resp.data.message)
              }
            })
          }
            // this.$message.success(resp.data.message)
         } else {
          console.log(resp)
          this.$message.error(resp.data.message)
        }
      })
      if(this.runflag === 1){
            console.log('定时器结束')
            //获取收益图表数据
            this.$http.get('getTradingAccountMsg?sessionToken='+this.SessionToken+'&recordId='+this.backtestId+'').then((resp) => {
              if (resp.data.status === 200) {
                this.drawdata=resp.data.data
                console.log(this.drawdata)
                let a = 0
                for(let i=0;i<this.drawdata.profitList.length;i++){
                  a=this.drawdata.profitList[i].profit+a
                  this.drawvalue.push(a)
                  this.drawdate.push(this.drawdata.profitList[i].date)
                }
                console.log(this.drawvalue,this.drawdate)
                this.drawbacktestcharts()
                // 获取回测结果数据
                this.$http.get('inquireTestRecordMsg?sessionToken='+this.SessionToken+'&recordId='+this.backtestId+'').then((resp) => {
                  if (resp.data.status === 200) {
                    this.backtestdate=resp.data.data
                    this.backtestdate.starttime = moment(new Date(parseInt(this.backtestdate.starttime))).format("YYYY-MM-DD")
                    this.backtestdate.endtime = moment(new Date(parseInt(this.backtestdate.endtime))).format("YYYY-MM-DD")
                    clearInterval(this.interval)
                  } else {
                    console.log(resp)
                    this.$message.error(resp.data.message)
                  }
                })
              } else {
                console.log(resp)
                this.$message.error(resp.data.message)
              }
            })
          }
    },
    getStratrgyCode (){
      this.$http.post('getCodeContent?sessionToken='+this.SessionToken+'&id='+this.strategyId+'').then((resp) => {
        if (resp.data.status === 200) {
          console.log(resp.data)
          this.content = resp.data.data.code
          if(resp.data.data.lastRecordId !== -1){
            this.backtestId = resp.data.data.lastRecordId
            if(this.backtestId !== null && this.backtestId !== ''){
              this.interval = setInterval(this.getOrderList,2000)
            }
          }
          this.$message.success(resp.data.message)
        } else {
          this.$message.error(resp.data.message)
        }
      })
    },
    editorInit () {
        require('brace/ext/language_tools')
        require('brace/mode/html')
        require('brace/mode/java')
        require('brace/mode/less')
        require('brace/theme/chaos')
        require('brace/snippets/java')
        var editor = ace.edit("editor");
        editor.$blockScrolling = Infinity;
        editor.setFontSize(24);
        editor.session.setMode("ace/mode/java");
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
    },
    changeData() {
      // this.content = value
      console.log(this.content)
      let obj = new Object()
      obj.strategyId = this.strategyId
      obj.javaFile = this.content
      console.log(typeof this.content)
      let param = JSON.stringify(obj)
      this.$http.post('updateStrategy?sessionToken='+this.SessionToken+'',param,{headers:{'Content-Type':'application/json'}}).then((resp) => {
        if (resp.data.status === 200) {
          console.log(resp)
          this.$message.success(resp.data.message)
        } else {
          console.log(resp)
          this.$message.error(resp.data.message)
        }
      })
    },
    setCompletions (editor, session, pos, prefix, callback) {//自动提示方法
　　　　callback(null, this.wordList.map(function (word) {
　　　　　　return {
　　　　　　　　caption: word.vl,
　　　　　　　　value: word.vl,
　　　　　　　　meta: word.meta
　　　　　　}
　　　　}))
　　},
    useronMouseOver() {
      this.userflag = true;
    },
    useronMouseOut() {
      this.userflag = false;
    },
    huiceliebiao() {
      this.$router.push('/backtest_detail')
    },
    yunxinghuice() {
      console.log(this.time)
      console.log(this.runTimeCycle)
      if(this.time !== '' || this.runTimeCycle !== ''){
        let obj = new Object()
        obj.strategyId = this.strategyId
        obj.javaFile = this.content
        obj.startDate = (this.time[0]).valueOf()
        obj.endDate = (this.time[1]).valueOf()
        obj.runTimeCycle = this.runTimeCycle
        let param = JSON.stringify(obj)
        console.log(param)
        this.$http.post('runStrategy?sessionToken='+this.SessionToken+'',param,{headers:{'Content-Type':'application/json'}}).then((resp) => {
          if (resp.data.status === 200) {
            console.log(resp.data)
            this.backtestId = resp.data.data
            localStorage.setItem('backtestId',resp.data.data)
            this.$router.push('/backtest_detail')
            this.$message.success(resp.data.message)
          } else {
            this.$message.error(resp.data.message)
          }
        })
      }
      
    },
    back() {
      this.$router.go(-1);
      clearInterval(this.interval)
    },
    drawbacktestcharts () {
      this.charts = this.$echarts.init(document.getElementById('backtest_chart'));
      this.charts.setOption( {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          // data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.drawdate
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
                        // name: '邮件营销',
            type: 'line',
            stack: '总量',
            data: this.drawvalue
          },
          // {
          //               // name: '联盟广告',
          //   type: 'line',
          //   stack: '总量',
          //               // data: [220, 182, 191, 234, 290, 330, 310]
          // },
          // {
          //               // name: '视频广告',
          //   type: 'line',
          //   stack: '总量',
          //               // data: [150, 232, 201, 154, 190, 330, 410]
          // },
          // {
          //   // name: '直接访问',
          //   type: 'line',
          //   stack: '总量',
          //   // data: [320, 332, 301, 334, 390, 330, 320]
          // },
          // {
          //   // name: '搜索引擎',
          //   type: 'line',
          //   stack: '总量',
          //   // data: [820, 932, 901, 934, 1290, 1330, 1320]
          // }
        ]

      });
    }
  }
};
</script>